import axios from 'axios'
// 创建axios实例。统一配置
import { Message } from 'element-ui'
import store from '@/store'
import { diffTokenTime } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL, // api的base_url
  timeout: 5000 // 请求超时时间
  // .... 其他信息
})
// request拦截器
service.interceptors.request.use(
  (config) => {
    if (localStorage.getItem('token')) {
      if (diffTokenTime()) {
        store.dispatch('app/logout')
        return Promise.reject(new Error('token 失效了'))
      }
    }
    config.headers.Authorization = localStorage.getItem('token')
    return config
  },
  (error) => {
    return Promise.reject(new Error(error))
  }
)

// respone拦截器
service.interceptors.response.use(
  (response) => {
    const { data, meta } = response.data
    if (meta.status === 200 || meta.status === 201) {
      return response.data
    } else {
      Message.error(meta.msg)
      return Promise.reject(new Error(meta.msg))
    }
  },
  (error) => {
    return Promise.reject(new Error(error))
  }
)

export default service
